package io.github.talelin.latticy.controller.api;

import io.github.talelin.core.annotation.AdminRequired;
import io.github.talelin.core.annotation.LoginRequired;
import io.github.talelin.latticy.bo.PageCounterBO;
import io.github.talelin.latticy.common.CommonUtil;
import io.github.talelin.latticy.dto.CreateCommonJobDTO;
import io.github.talelin.latticy.dto.UpdateCommonJobDTO;
import io.github.talelin.latticy.entity.CommonJob;
import io.github.talelin.latticy.service.CommonJobService;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;

@RestController
@RequestMapping("/api/common-job")
@Validated
public class CommonJobController {

    @Autowired
    private CommonJobService commonJobService;

    /**
     * 发布公域任务
     */
    @PostMapping
    @LoginRequired
    public CreatedVO create(@RequestBody @Validated CreateCommonJobDTO dto) {
        commonJobService.create(dto);
        return new CreatedVO<>();
    }

    @PutMapping("/editor/{id}")
    @LoginRequired
    public UpdatedVO edit(@RequestBody @Validated CreateCommonJobDTO dto,
                          @PathVariable @Positive Long id) {
        commonJobService.edit(id, dto);
        return new UpdatedVO<>();
    }

    /**
     * 公域任务列表
     */
    @GetMapping("/page")
    @LoginRequired
    public PageResponseVO page(@RequestParam(defaultValue = "0", required = false) int start,
                     @RequestParam(defaultValue = "20", required = false) int count,
                     @RequestParam(name = "is_getting", defaultValue = "false") Boolean isGetting) {
        PageCounterBO pageCounter = CommonUtil.converToPageParamter(start, count);
        Page<CommonJob> paging = commonJobService.getAll(pageCounter.getPage(), pageCounter.getSize(), isGetting);
        return new PageResponseVO<>(paging.getTotalElements(), paging.getContent(), paging.getNumber(), paging.getSize());
    }

    /**
     * 领取公域任务
     */
    @PutMapping("/{id}")
    @LoginRequired
    public UpdatedVO update(@PathVariable @Positive Long id,
                       @RequestBody @Validated UpdateCommonJobDTO dto) {
        commonJobService.updated(dto, id);
        return new UpdatedVO<>();
    }

}
